import 'package:lib_util/utils/utils.dart';
import 'package:objectbox/objectbox.dart';
import 'package:lib_database/objectbox.g.dart';
import '../basemodel.dart';
import '../../config.dart';

@Entity()
class DappToken {
  @Id()
  int id;
  int chainId;
  String contract; //合约地址
  String name; //名称
  String symbol; //简称
  String? logo; //封面
  String? balance; //代币持仓数量
  int decimals;

  DappToken({
    this.id = 0,
    required this.chainId,
    required this.contract,
    required this.name,
    required this.symbol,
    this.logo,
    this.balance,
    this.decimals = 0,
  });

  @override
  String toString() {
    return 'Token{id: $id, chainId: $chainId, contract: $contract, name: $name, symbol: $symbol, logo: $logo, balance: $balance, decimals: $decimals,';
  }

  String getShowName() {
    return Utils.isNotEmpty(symbol) ? symbol : name;
  }

  String getFormatBalance() {
    return Utils.isEmpty(balance)
        ? '0.00'
        : Utils.formatStringBalance(balance!, fractionDigits: Config.balanceFixedNum);
  }
}

class DappTokenModel extends BaseModel<DappToken> {
  DappTokenModel(Box<DappToken> box) : super(box);

  DappToken? getTokenById(int id) {
    return box.get(id);
  }

  DappToken? getTokenByContract(String contract) {
    List<DappToken> list = getTokenList();
    // if (list.isEmpty) return null;
    if (list.isNotEmpty) {
      DappToken token = list.lastWhere((element) {
        return element.contract == contract;
      });

      return token;
    }
    return null;
  }

  DappToken? getTokenByIdContract(int chainId, String contract) {
    return box.query(DappToken_.chainId.equals(chainId) & DappToken_.contract.equals(contract)).build().findFirst();
  }

  List<DappToken> getTokenList() {
    return box.getAll();
  }

  List<int> putTokenList(List<DappToken> tokens) {
    return box.putMany(tokens);
  }

  addToken(DappToken token) {
    return box.put(token, mode: PutMode.insert);
  }

  addTokenList(List<DappToken> tokens) {
    box.putMany(tokens, mode: PutMode.insert);
  }

  updateToken(DappToken token) {
    box.put(token, mode: PutMode.update);
  }

  updateAsyncToken(DappToken token) {
    box.putAsync(token, mode: PutMode.update);
  }

  deleteToken(int tokenId) {
    box.remove(tokenId);
  }

  deleteTokenList(List<int> ids) {
    box.removeMany(ids);
  }
}
